package com.ryujung.binary_tree.leetCode_230;

import java.util.Deque;
import java.util.LinkedList;


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    // BST的中序遍历就是有序的数组，所以直接获取中序遍历的第k个元素即可
    public int kthSmallest(TreeNode root, int k) {
        if (root == null) return Integer.MIN_VALUE;

        Deque<TreeNode> stk = new LinkedList<>();
        int i = 0;
        while (!stk.isEmpty() || root != null) {
            while (root != null) {
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            if (++i == k) {
                return root.val;
            }
            root = root.right;
        }
        return 0;
    }
    // 时间复杂度：O(h + k)
    // 空间复杂度：O(h)栈空间为树的高度，min：平衡树 logn， max：链树 n
}